package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.behavior.dtos.FollowBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApFollowBehavior;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Transactional
@Service
@Slf4j
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public void follow(FollowBehaviorDto dto) {
        //1.判断参数
        if(dto==null){
            log.info("[关注行为]参数非法" );
            return;
        }

        //2.查询行为实体判断是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(dto.getUserId(), null);
        if(apBehaviorEntry==null){
            log.info("[关注行为]行为实体不存在");
            return;
        }

        //3.查询关注行为数据
        ApFollowBehavior apFollowBehavior = getOne(Wrappers.<ApFollowBehavior>lambdaQuery()
                .eq(ApFollowBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApFollowBehavior::getFollowId, dto.getFollowId())
                .eq(ApFollowBehavior::getArticleId, dto.getArticleId()));

        //4.如果关注行为数据不存在，就创建
        if(apFollowBehavior==null){
            if(dto.getOperation()==1){
                log.info("数据不存在，不能取消关注" );
                return;
            }

            //数据不存在时，用户关注，就要保存数据
            apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setEntryId(apBehaviorEntry.getId());//行为实体ID
            apFollowBehavior.setFollowId(dto.getFollowId());//作者用户ID
            apFollowBehavior.setArticleId(dto.getArticleId());//文章ID
            apFollowBehavior.setCreatedTime(new Date());
            save(apFollowBehavior);

        } else {//5.如果关注行为数据存在，就删除
            if(dto.getOperation()==0){
                log.info("数据已存在，不要重复关注");
                return;
            }

            //数据存在时，用户取消关注，就删除
            removeById(apFollowBehavior.getId());
        }
    }
}
